// pages/classroom/classroom.js
import Notify from '@vant/weapp/notify/notify';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        roomList: [],
        allRoomList: [],
        option1: [
            { text: '全部教学楼', value: '0' }
        ],
        option2: [
            { text: '全部朝向', value: '0' },
            { text: '朝东', value: '1' },
            { text: '朝西', value: '2' },
            { text: '朝南', value: '3' },
            { text: '朝北', value: '4' }
        ],
        value1: '0',
        value2: '0',
        searchTips: null,
        minHour: 10,
        maxHour: 20,
        minDate: new Date().getTime(),
        maxDate: new Date(2019, 10, 1).getTime(),
        currentDate: new Date().getTime(),
        feeRoomOrder: false,
        feeRoomSelectStart: {timestamp: null, formatstamp: null},
        feeRoomSelectEnd: {timestamp: null, formatstamp: null},
        TimeShowDialog: false,
        orderTimeSelectFlag: 0,
        feeCanderSelectFlag: false,
        // 添加方向映射
        directionMap: {
            '朝东': '1',
            '朝西': '2',
            '朝南': '3',
            '朝北': '4'
        },
        buildings: [
            { id: 0, name: '全部' }
        ],
        selectedBuildingIndex: 0,
        directions: [
            { id: 0, name: '全部' },
            { id: 1, name: '朝东' },
            { id: 2, name: '朝西' },
            { id: 3, name: '朝南' },
            { id: 4, name: '朝北' }
        ],
        selectedDirectionIndex: 0,
        // 添加朝向映射
        directionMapping: {
            'east': '朝东',
            'west': '朝西',
            'south': '朝南',
            'north': '朝北'
        },
        searchValue: '', // 搜索关键词
        filteredRoomList: [], // 存储过滤后的教室数据
    },
    
    showFeeRoomButton(){
        this.setData({
            feeRoomOrder:true
        })
    },

    onCloseFeeRoomOrder(){
        this.setData({
            feeRoomOrder:false
        })
    },
    /* 预约时间选择触发按钮 */
    fullTimeSelect(e){
        this.setData({
            TimeShowDialog:true,
            orderTimeSelectFlag:e.currentTarget.dataset.flag
        })
    },
    /* 关于时间选择器按钮 */
    onCloseTimeShowDialog(){
        this.setData({
            TimeShowDialog:false
        })
    },
    /* 关于时间选择回调 */
    onInputOrderSelectTime(event){
        console.log(event);
        this.setData({
            currentDate: event.detail,
            
        });
    },
    /* 关于选择时间确定 */
    confirmSelectTime(e){
        var timeString = this.formatTimestamp(this.data.currentDate)
        console.log("时间为",timeString);
        if(this.data.orderTimeSelectFlag == "0"){
            this.setData({
                feeRoomSelectStart:{timestamp:this.data.currentDate,formatstamp:timeString}
            })
        }else{
            if(this.data.feeRoomSelectStart.timestamp>=this.data.currentDate){
                wx.showToast({
                  title: '结束不能大于开始',
                  icon:"none"
                })
                return
            }
            this.setData({
                feeRoomSelectEnd:{timestamp:this.data.currentDate,formatstamp:timeString}
            })
        }
        this.setData({
            TimeShowDialog:false
        })
    },
    /**
         * 将时间戳转换为 年月日 时分 格式
         * @param {number} timestamp - 时间戳，单位为毫秒
         * @returns {string} 格式化后的日期字符串，格式为 YYYY-MM-DD HH:mm
     */
    formatTimestamp(timestamp) {
        // 创建一个 Date 对象
        const date = new Date(timestamp);

        // 获取年、月、日、小时、分钟
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');  // 月份从0开始，需要加1并补零
        const day = String(date.getDate()).padStart(2, '0');  // 补零
        const hours = String(date.getHours()).padStart(2, '0');  // 补零
        const minutes = String(date.getMinutes()).padStart(2, '0');  // 补零

        // 格式化并返回
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    /* 查询教室 */
    searchOrderRoom(){
        
        let second = 3;
        const timer = setInterval(() => {
            second--;
            if (second) {
                wx.showLoading({
                    title:"查询中"
                })
            } else {
                clearInterval(timer);
                this.onCloseFeeRoomOrder({})
                wx.hideLoading()
            }
        }, 1000);
    },
    /* 空教室日历查询开启 */
    showFeeCanderButton(){
        this.setData({
            feeCanderSelectFlag:true
        })
    },
    /* 空教室日历查询关闭 */
    onCloseFeeRoomCander(){
        this.setData({
            feeCanderSelectFlag:false
        })
    },
    /* 空教室查询确定选择的日期 */
    onConfirmFeeRoomCander(event){
        console.log(event.detail);
        var selectConfirmDateFormat = this.formatDateCander(event.detail)
        console.log(selectConfirmDateFormat);
        let second = 3;
        const timer = setInterval(() => {
            second--;
            if (second) {
                wx.showLoading({
                    title:"查询中"
                })
            } else {
                clearInterval(timer);
                this.onCloseFeeRoomCander({})
                wx.hideLoading()
            }
        }, 1000);
        
    },
    /* 日期转换 */
    formatDateCander(date) {
        date = new Date(date);
        let second = 3;
        
        return `${date.getMonth() + 1}-${date.getDate()}`;
        
    },
    /* 收藏教室 */
    collectRoom(e) {
        const index = e.currentTarget.dataset.index;
        const room = this.data.roomList[index];
        const userInfo = wx.getStorageSync('userInfo');
        
        if (!userInfo || !userInfo.id) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        // 根据当前收藏状态决定是收藏还是取消收藏
        if (room.isCollected) {
            // 取消收藏
            wx.request({
                url: `${getApp().globalData.baseUrl}/admin/favorites/delete`,
                method: 'DELETE',
                data: {
                    userId: userInfo.id,
                    roomId: room.id
                },
                success: (res) => {
                    if (res.data.code === 200) {
                        // 更新本地收藏状态
                        const newRoomList = [...this.data.roomList];
                        newRoomList[index].isCollected = false;
                        this.setData({
                            roomList: newRoomList,
                            [`allRoomList[${index}].isCollected`]: false
                        });
                        
                        Notify({ type: 'success', message: '已取消收藏' });
                    } else {
                        Notify({ type: 'error', message: res.data.message || '取消收藏失败' });
                    }
                },
                fail: () => {
                    Notify({ type: 'error', message: '网络请求失败' });
                }
            });
        } else {
            // 添加收藏
            wx.request({
                url: `${getApp().globalData.baseUrl}/admin/favorites/add`,
                method: 'POST',
                data: {
                    userId: userInfo.id,
                    roomId: room.id,
                    buildingId: room.buildingId
                },
                success: (res) => {
                    if (res.data.code === 200) {
                        // 更新本地收藏状态
                        const newRoomList = [...this.data.roomList];
                        newRoomList[index].isCollected = true;
                        this.setData({
                            roomList: newRoomList,
                            [`allRoomList[${index}].isCollected`]: true
                        });
                        
                        Notify({ type: 'success', message: '收藏成功' });
                    } else {
                        Notify({ type: 'error', message: res.data.message || '收藏失败' });
                    }
                },
                fail: () => {
                    Notify({ type: 'error', message: '网络请求失败' });
                }
            });
        }
    },
    /* 立刻修复 */
    fixNowClick(e){
        console.log(e.currentTarget.dataset.index);
        var infoTemp = this.data.roomList[e.currentTarget.dataset.index]
        wx.navigateTo({
            url: `/pages/addfix/addfix?build=${infoTemp.buildNumber}&roomName=${infoTemp.roomNumber}`,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getBuildings();
        this.getRoomsDetail();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 获取所有教室详细信息
    getRoomsDetail() {
        wx.showLoading({
            title: '加载中...'
        });

        const userInfo = wx.getStorageSync('userInfo');

        wx.request({
            url: `${getApp().globalData.baseUrl}/admin/rooms/detail`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    // 转换数据格式并保存所有数据
                    const formattedRooms = res.data.data.list.map(item => ({
                        id: item.roomId,
                        buildingId: item.buildingId,
                        buildNumber: item.buildingName,
                        roomNumber: item.roomName,
                        roomInfo: this.data.directionMapping[item.direction.toLowerCase()] || item.direction,
                        maxNum: item.maxCapacity,
                        nowMun: item.currentBookingCount,
                        hasCourse: item.hasCourse,
                        courseName: item.courseName,
                        teacherName: item.teacherName,
                        isCollected: false
                    }));

                    this.setData({
                        allRoomList: formattedRooms,
                        roomList: formattedRooms
                    }, () => {
                        // 获取完教室列表后，检查收藏状态
                        if (userInfo && userInfo.id) {
                            this.checkFavoriteStatus();
                        }
                    });
                } else {
                    wx.showToast({
                        title: '获取教室列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            },
            complete: () => {
                wx.hideLoading();
            }
        });
    },

    // 检查收藏状态
    checkFavoriteStatus() {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo.id) return;

        this.data.roomList.forEach((room, index) => {
            wx.request({
                url: `${getApp().globalData.baseUrl}/admin/favorites/check`,
                method: 'GET',
                data: {
                    userId: userInfo.id,
                    roomId: room.id
                },
                success: (res) => {
                    if (res.data.code === 200) {
                        // 更新收藏状态
                        const newRoomList = [...this.data.roomList];
                        newRoomList[index].isCollected = res.data.data.isCollected;
                        this.setData({
                            roomList: newRoomList,
                            [`allRoomList[${index}].isCollected`]: res.data.data.isCollected
                        });
                    }
                }
            });
        });
    },

    // 获取教学楼列表
    getBuildings() {
        wx.request({
            url: `${getApp().globalData.baseUrl}/admin/buildings`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    const buildingsList = res.data.data.list.map(item => ({
                        id: item.id,
                        name: item.name
                    }));
                    
                    // 将"全部"选项和获取的教学楼列表合并
                    this.setData({
                        buildings: [{ id: 0, name: '全部' }, ...buildingsList]
                    });
                } else {
                    wx.showToast({
                        title: '获取教学楼列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },

    // 教学楼筛选变化
    onBuildingChange(e) {
        const index = e.detail.value
        this.setData({
            selectedBuildingIndex: index
        })
        this.filterRooms()
    },

    // 朝向筛选变化
    onDirectionChange(e) {
        const index = e.detail.value
        this.setData({
            selectedDirectionIndex: index
        })
        this.filterRooms()
    },

    // 筛选房间（前端筛选）
    filterRooms() {
        const selectedBuilding = this.data.buildings[this.data.selectedBuildingIndex];
        const selectedDirection = this.data.directions[this.data.selectedDirectionIndex];
        const searchValue = this.data.searchValue.toLowerCase();

        let filteredRooms = this.data.allRoomList;

        // 按教学楼筛选
        if (selectedBuilding.id !== 0) {
            filteredRooms = filteredRooms.filter(room => 
                room.buildNumber === selectedBuilding.name
            );
        }

        // 按朝向筛选
        if (selectedDirection.id !== 0) {
            filteredRooms = filteredRooms.filter(room => 
                room.roomInfo === selectedDirection.name
            );
        }

        // 按搜索关键词筛选
        if (searchValue) {
            filteredRooms = filteredRooms.filter(room => 
                room.buildNumber.toLowerCase().includes(searchValue) ||
                room.roomNumber.toLowerCase().includes(searchValue) ||
                room.roomInfo.toLowerCase().includes(searchValue)
            );
        }

        // 更新显示的教室列表
        this.setData({
            roomList: filteredRooms
        });
    },

    // 添加报修方法
    repairRoom(e) {
        console.log("点击和内容",e);
        const { buildingId, buildNumber, nowMun, roomNumber } = e.currentTarget.dataset.info
        wx.navigateTo({
            url: `/pages/addfix/addfix?buildingId=${buildingId}&buildingName=${buildNumber}&roomId=${nowMun}&roomName=${roomNumber}`
        })
    },

    /* 教师预约 */
    navPreOrderRoom(e) {
        const { buildingid, roomid } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/preorderroom/preorderroom?buildingId=${buildingid}&roomId=${roomid}`,
        })
    },

    // 搜索输入处理
    onSearchChange(e) {
        const searchValue = e.detail.trim()
        this.setData({ searchValue })
        this.filterRooms()
    },

    // 搜索取消处理
    onSearchCancel() {
        this.setData({ searchValue: '' })
        this.filterRooms()
    },
})